package com.okhttp.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * @author GYL
 * @dateTime 2020/4/22-14:49
 * @description
 */
public class Utils {
  /**
   * 关闭流
   * @param ios
   * @return
   */
  public static boolean close(Closeable... ios) {
    if (ios != null) {
      for (Closeable closeable : ios) {
        try { closeable.close(); } catch (Exception e) {}
      }
    }
    return true;
  }

  public static Object clone(Serializable obj) {
    Object clone = cloneObject(obj);
    if (clone == null) {
      clone = cloneObject(obj);
    }
    return clone;
  }

  public static Object cloneObject(Serializable obj) {
    Object anotherObj = null;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = null;

    ObjectInputStream ois = null;
    try {
      oos = new ObjectOutputStream(baos);
      oos.writeObject(obj);
      byte[] bytes = baos.toByteArray();

      ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

      ois = new ObjectInputStream(bais);
      anotherObj = ois.readObject();
    } catch (IOException ex) {
      throw new RuntimeException(ex.getMessage(), ex);
    } catch (ClassNotFoundException ex) {
      throw new RuntimeException(ex.getMessage(), ex);
    } catch (StackOverflowError error) {
      System.out.println("stack length " + error.getStackTrace().length);
      error.printStackTrace();
      return null;
    } finally {
      close(oos,ois);
    }
    return anotherObj;
  }

}
